//
//  SHCreditCardSearchController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2017/11/30.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//
#import "SHBankInfoModel.h"
#import "SHTextField.h"
#import "SHCreditCardSearchCell.h"
#import "SHCreditCardSearchController.h"

@interface SHCreditCardSearchController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)UITableView *  cardMangerTable;
@property(nonatomic,strong)NSMutableArray  *creditCardArray;
@property(nonatomic,strong)NSMutableArray  *searchResultArray;
@property(nonatomic,getter=isSearch)BOOL  search;
@property(nonatomic,strong)NSString  *bankKeyword;


@end

@implementation SHCreditCardSearchController
{
    SHTextField      *_searcTf;
    UIBarButtonItem  *_searchItem;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"搜索";
    [self configSearchBtn];
    [self createTopSerchTextField];
    [self cardMangerTable];
    [self getMainBankCardName];
}

- (void)getMainBankCardName{
    
    
    [MyDataService requestNoRSAAFURL:@"/data/api/get_bank_cnaps_code" httpMethod:@"GET" params:@{@"bank_level":@(1)} data:nil complection:^(id result) {
        
        if ([result isKindOfClass:[NSDictionary class]]) {
            BOOL succesed = [result[@"success"]boolValue];
            if (succesed) {
                
                self.creditCardArray  = [SHBankInfoModel mj_objectArrayWithKeyValuesArray:result[@"data"]];
                [self.cardMangerTable reloadData];

            }else{
                [self.view makeToast:result[@"data"] duration:1.5 position:@"center"];
            }
            
        }
    } failure:^(id erro) {
        
        
    }];
    
    
}


#pragma mark - 设置搜索按钮
- (void)configSearchBtn{
   
    UIBarButtonItem *searchItem =  [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchKeyWordAction:)];
    [searchItem setTitleTextAttributes:@{NSForegroundColorAttributeName:KSHTEXTCOLOR,NSFontAttributeName : KSystemFont(13)} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = searchItem;
    _searchItem = searchItem;
}

- (void)backAction:(UIBarButtonItem *)item{
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 头部搜索款
- (void)createTopSerchTextField{
    
    UIView *searchBg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, __I6Width(280),30)];
    
    searchBg.layer.borderWidth = 1;
    searchBg.layer.borderColor = KLINECOLOR.CGColor;
    searchBg.layer.cornerRadius = 15;
    searchBg.layer.masksToBounds = YES;
    self.navigationItem.titleView = searchBg;
    UIImageView *searchLogoImgView = [[UIImageView alloc]initWithFrame:CGRectMake(__I6Width(10), 7,16,16 )];
    searchLogoImgView.image = [UIImage imageNamed:@"cs_searchbar"];
    [searchBg addSubview:searchLogoImgView];
    SHTextField *searcTf = [[SHTextField  alloc]initWithFrame:CGRectMake(__I6Width(20) + 16 ,0, __I6Width(280) - __I6Width(25), 30)];
    searcTf.delegate = self;
    searcTf.font = KSHSystemFont(15);
    NSNumber * value = [NSNumber numberWithInteger:NSTextAlignmentCenter];
    [searcTf setValue:value forKeyPath:@"_placeholderLabel.textAlignment"];
    searcTf.textAlignment = NSTextAlignmentLeft;
    searcTf.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [searcTf setPlaceholder:@"请输入总行名称" font:15 textColor:KSHTEXTPLACEHOLDERCOLOR];
    [searchBg addSubview:searcTf];
    _searcTf = searcTf;
}







#pragma mark - 卡片数组
- (NSMutableArray *)creditCardArray{
    
    if (!_creditCardArray) {
        
        _creditCardArray = [NSMutableArray arrayWithCapacity:10];
    }
    
    return _creditCardArray;
}

- (NSMutableArray *)searchResultArray{
    
    if (!_searchResultArray) {
        
        _searchResultArray = [NSMutableArray arrayWithCapacity:10];
    }
    
    return _searchResultArray;
}

#pragma mark - 卡片管理列表
- (UITableView *)cardMangerTable{
    
    if (!_cardMangerTable) {
        
        _cardMangerTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - KSAFEHEIGHT - KNAVIGATIONBARHEIGHT ) style:UITableViewStylePlain];
        _cardMangerTable.delegate = self;
        _cardMangerTable.dataSource = self;
        _cardMangerTable.rowHeight = __I6Height(50);
        [self.view addSubview:_cardMangerTable];
        _cardMangerTable.separatorStyle =  UITableViewCellSeparatorStyleNone;
        [_cardMangerTable registerClass: [SHCreditCardSearchCell  class]  forCellReuseIdentifier:@"creditCardSearch"];
        
    }
    return _cardMangerTable;
}



#pragma mark --- UITablView  & DataSource  & Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  
    return  self.isSearch ? self.searchResultArray.count :  self.creditCardArray.count ;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SHCreditCardSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"creditCardSearch"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SHBankInfoModel *creditCardModel;
    if (self.isSearch) {
        creditCardModel = self.searchResultArray[indexPath.row];

    }else{
        creditCardModel = self.creditCardArray[indexPath.row];

        
    }
    [cell setLeftImgWithImgName:@"" title:creditCardModel.bankName];
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isSearch) {
        
        SHBankInfoModel *creditCardModel = self.searchResultArray[indexPath.row];
        if ([_delegate respondsToSelector:@selector(searchResultCardModel:)]) {
            [_delegate searchResultCardModel:creditCardModel];
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        SHBankInfoModel *creditCardModel = self.creditCardArray[indexPath.row];
        if ([_delegate respondsToSelector:@selector(searchResultCardModel:)]) {
            [_delegate searchResultCardModel:creditCardModel];
        }
        [self.navigationController popViewControllerAnimated:YES];
        
        
        
    }
    
    
   
   
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    return  YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (string.length == 0) {
        
        
        _search = NO;
        _searchItem.title = @"搜索";
        [self.cardMangerTable reloadData];
        
    }
    return YES;
}

#pragma mark - 点击搜索开始筛选
- (void)searchKeyWordAction:(UIBarButtonItem *)item{
    
    _bankKeyword = _searcTf.text;

    if (!_bankKeyword || [_bankKeyword isEqualToString:@""]) {
        [self.view makeToast:@"请输入总行名称" duration:2.f position:@"center"];
        return;
    }

    if ([item.title isEqualToString:@"搜索"]) {
        _search = YES;
        item.title = @"取消";
        [_searcTf resignFirstResponder];
        [self.searchResultArray removeAllObjects];
        for (int i = 0 ; i < self.creditCardArray.count ; i ++) {
            SHBankInfoModel *creditCardMode = self.creditCardArray[i];
            if ([creditCardMode.bankName containsString:_bankKeyword]) {
                [self.searchResultArray addObject:creditCardMode];
            }
        }
        for (SHBankInfoModel *model in self.searchResultArray) {
            SHLog(@"====%@",model.bankName);
        }
        [self.cardMangerTable reloadData];

    }else{
        
        _search = NO;
        _searcTf.text = @"";
        item.title = @"搜索";
        [self.cardMangerTable reloadData];
        
    }
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
